package com.ctl.szmd.szmd.feature_wm.ui.viewmodel

import android.annotation.SuppressLint
import android.os.Build
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.NetworkUtils
import com.ctl.lib_common.utils.LocalCache
import com.ctl.lib_common.utils.MD5
import com.ctl.lib_common.utils.http.doFailure
import com.ctl.lib_common.utils.http.doSuccess
import com.ctl.szmd.szmd.feature_wm.Constants
import com.ctl.szmd.szmd.feature_wm.data.model.WmDataModel
import com.ctl.szmd.szmd.feature_wm.data.repository.WmRepository
import com.ctl.szmd.szmd.feature_wm.ui.base.BaseWmViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart

/**
 * created by : chentl
 * Date: 2020/07/22
 */
class WmLoginViewModel(private val repository: WmRepository) : BaseWmViewModel() {

    var userName = MutableLiveData<String>()
    var userPw = MutableLiveData<String>()
    var isRemember = MutableLiveData<Boolean>()
    val mLoading = ObservableBoolean()

    private val _login = MutableLiveData<WmDataModel>()
    private val _failure = MutableLiveData<String>()
    val failure = _failure
    val login = _login

    init {
        userName.value = LocalCache.getInstance().getString(Constants.LOCAL_CACHE_MW_LOGIN_PHONE)
        userPw.value = LocalCache.getInstance().getString(Constants.LOCAL_CACHE_MW_LOGIN_PASSWORD)
        isRemember.value =
            LocalCache.getInstance().getBoolean(Constants.LOCAL_CACHE_MW_LOGIN_REMEMBER)
    }


    @SuppressLint("MissingPermission")
    @ExperimentalCoroutinesApi
    fun getLoginInfo() = liveData {
        val map = mutableMapOf<String, Any>()
        map.put("AppId", "Fulian")
        map.put("Phone", userName.value.toString())
        map.put("Password", MD5.md5(userPw.value.toString()))
        map.put("Platform", "Android" + Build.VERSION.RELEASE)
        map.put("Version", AppUtils.getAppVersionName())
        map.put("IpAddress", NetworkUtils.getIPAddress(true))
        repository.getLoginInfo(map)
            .onStart {
                // 在调用 flow 请求数据之前，做一些准备工作，例如显示正在加载数据的按钮
                mLoading.set(true)
            }
            .catch {
                // 捕获上游出现的异常
                mLoading.set(false)
            }
            .onCompletion {
                // 请求完成
                mLoading.set(false)
            }
            .collectLatest { result ->
                result.doFailure { throwable ->
                    _failure.value = throwable?.message ?: "failure"
                }
                result.doSuccess { value ->
                    _login.postValue(value)
                    emit(value)
                }
            }
    }

}